<template>
	<div class="sku">
		<el-page-header title="返回商品列表" content="编辑商品" @back="$router.back()"></el-page-header>
		<el-form ref="formRef" style="margin-top:20px" :model="formData" :rules="formRules" label-width="auto">
			<el-tabs v-model="activeTab">
				<el-tab-pane label="基本信息" name="1">
					<el-row type="flex" :gutter="10" style="margin-top:30px">
						<el-col :span="20" :offset="2">
							<el-form-item label="商品名称" prop="goods_name">
								<el-input v-model="formData.goods_name" clearable placeholder="请输入商品名称"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="20" :offset="2">
							<el-form-item label="商品图片" prop="imagesIds">
								<el-upload-image v-model="formData.goods_images" :limit="5"
									:title="title"></el-upload-image>
							</el-form-item>
						</el-col>
						<el-col :span="20" :offset="2">
							<el-form-item label="商品限购数量" prop="purchase_num">
								<el-input v-model="formData.purchase_num" clearable placeholder="为0或不填写表示不限购"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="20" :offset="2" v-if="$store.state.type == 0">
							<el-form-item label="商品所属" prop="goods_type">
								<el-select v-model="formData.goods_type" placeholder="请选择">
									<el-option v-for="(item, index) in sourcelist" :key="item.id" :label="item.title"
										:value="item.id"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="20" :offset="2">
							<el-form-item label="商品分类" prop="categoryIds">
								<el-cascader v-model="formData.categoryIds" :options="goodsTypeData"
									:props="props"></el-cascader>
								<!-- <el-cascader v-model="formData.categoryIds" :options="goodsTypeData" ></el-cascader> -->
							</el-form-item>
						</el-col>
						<el-col :span="20" :offset="2">
							<el-form-item label="自编码" prop="goods_no">
								<el-input v-model="formData.goods_no" clearable placeholder="请输入自编码"></el-input>
							</el-form-item>
						</el-col>
						<!-- <el-col :span="20" :offset="2">
						    <el-form-item label="来源备注" prop="source_name">
						        <el-input
						            v-model="formData.source_name"
						            clearable
						            placeholder="请输入来源备注"
						        ></el-input>
						    </el-form-item>
						</el-col> -->
						<el-col :span="20" :offset="2">
							<el-form-item label="商品状态" prop="status">
								<el-radio-group v-model="formData.status">
									<el-radio :label="10">上架</el-radio>
									<el-radio :label="20">下架</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<!-- is_special 是否特价商品0否 1是 is_recommend  是否推荐 0否 1是 -->
						<!-- <el-col :span="20" :offset="2">
						    <el-form-item label="是否是推荐商品" prop="is_recommend">
						        <el-radio-group v-model="formData.is_recommend">
						            <el-radio :label="1">是</el-radio>
						            <el-radio :label="0">否 </el-radio>
						        </el-radio-group>
						    </el-form-item>
						</el-col> -->
						<!-- goods_stuff 好货推荐 0否 1是 -->
						<!-- <el-col :span="20" :offset="2">
						    <el-form-item label="是否是好货推荐商品" prop="goods_stuff">
						        <el-radio-group v-model="formData.goods_stuff">
						            <el-radio :label="1">是</el-radio>
						            <el-radio :label="0">否 </el-radio>
						        </el-radio-group>
						    </el-form-item>
						</el-col> -->
						<el-col :span="20" :offset="2">
							<el-form-item label="是否赠送积分" prop="is_points_gift">
								<el-radio-group v-model="formData.is_points_gift">
									<el-radio :label="1">是</el-radio>
									<el-radio :label="0">否 </el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :span="20" :offset="2">
							<el-form-item label="是否是积分商品" prop="is_points_discount">
								<el-radio-group v-model="formData.is_points_discount">
									<el-radio :label="1">是</el-radio>
									<el-radio :label="0">否 </el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<!-- 	<el-col :span="20" :offset="2">
							<el-form-item label="会员折扣" prop="is_enable_grade">
								<el-radio-group v-model="formData.is_enable_grade">
									<el-radio :label="1">开启</el-radio>
									<el-radio :label="0">关闭</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col> -->
					</el-row>
				</el-tab-pane>
				<el-tab-pane label="规格/库存" name="2">
					<el-row :gutter="10" style="margin-top:30px">
						<el-col :span="20" :offset="2">
							<el-form-item label="规格类型" prop="spec_type">
								<el-radio-group v-model="formData.spec_type">
									<el-radio :label="10">单规格</el-radio>
									<el-radio :label="20">多规格</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<template v-if="formData.spec_type === 10">
							<el-col :span="20" :offset="2">
								<el-form-item label="商品价格" prop="goods_price">
									<el-input v-model="formData.goods_price" placeholder="请输入"
										@input="changeValuegoods_price">
										<template slot="append">元</template>
									</el-input>
								</el-form-item>
							</el-col>
							<!-- <el-col :span="20" :offset="2">
								<el-form-item label="进货价" prop="line_price">
									<el-input v-model="formData.line_price" placeholder="请输入"
										@input="changeValueline_price">
										<template slot="append">元</template>
									</el-input>
								</el-form-item>
							</el-col> -->
							<el-col :span="20" :offset="2">
								<el-form-item label="划线价" prop="line_price">
									<el-input v-model="formData.agent_price" placeholder="请输入"
										@input="changeValueagent_price">
										<template slot="append">元</template>
									</el-input>
								</el-form-item>
							</el-col>
							<el-col :span="20" :offset="2">
								<el-form-item label="商品重量" prop="goods_weight">
									<el-input v-model="formData.goods_weight" placeholder="请输入"
										@input="changeValuegoods_weight"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="20" :offset="2">
								<el-form-item label="库存量" prop="stock_num">
									<el-input v-model="formData.stock_num" placeholder="请输入"
										@input="changeValuestock_num"></el-input>
								</el-form-item>
							</el-col>
						</template>
						<template v-else>
							<el-col :span="20" :offset="2">
								<div class="sku_container">
									<div class="sku_group mb10" v-for="(spec, index) in specification" :key="spec.id">
										<div class="spec_title">
											<span class="label">规格名：</span>
											<el-input class="input" placeholder="请输入规格名" v-model.trim="spec.value">
											</el-input><span class="remove" @click="delSepc(index)">×</span>
										</div>
										<div class="group_container">
											<span class="label">规格值：</span>
											<el-popover placement="bottom" width="120" trigger="click" v-for="(option,
												option_index) in spec.leaf" :key="option_index">
												<el-input v-model.trim="option.value" :style="{ width: '110px' }">
												</el-input>
												<div class="sku_item" slot="reference">
													<span class="remove" @click.stop="
														delOption(
															index,
															option_index
														)
														">×</span>
													<div class="text">
														{{ option.value || option.spec_value }}
													</div>
												</div>
											</el-popover>
											<el-input class="input" suffix-icon="el-icon-plus"
												v-model="addValues[index]" placeholder="多个产品属性以空格隔开"
												@keyup.native.enter="
													addOption(index)
													" @blur="addOption(index)"></el-input>
										</div>
									</div>
									<div class="spec_title">
										<el-button type="primary" icon="el-icon-plus" :disabled="disabled"
											@click="addSpec">添加规格项目</el-button>
									</div>
								</div>
								<div class="sku_container" v-if="false">
									<SkuSelect :skusData="specificationFilter"></SkuSelect>
								</div>
								<div class="sku_container">
									<SkuTable ref="skuTable" :datalist="datalist" :skusData="specificationFilter">
									</SkuTable>
								</div>
							</el-col>
						</template>
					</el-row>
				</el-tab-pane>
				<el-tab-pane label="商品详情" name="3">
					<el-row :gutter="10">
						<el-col :span="20" :offset="2">
							<div style="border: 1px solid #ccc;">
								<Toolbar style="border-bottom: 1px solid #ccc" :editor="editor"
									:defaultConfig="toolbarConfig" :mode="mode" />
								<Editor style="height: 500px; overflow-y: auto;" v-model="formData.content"
									:defaultConfig="editorConfig" :mode="mode" @onCreated="onCreated" />
							</div>
						</el-col>
					</el-row>
				</el-tab-pane>
			</el-tabs>
		</el-form>
		<el-row :gutter="10" style="margin-top:20px;">
			<el-col :span="20" :offset="2">
				<el-button @click="submit" type="primary">提交</el-button>
			</el-col>
		</el-row>
	</div>
</template>

<script>
	/* @eslint-disabled */
	import SkuSelect from "@/components/sku-select";
	import SkuTable from "@/components/sku-table";
	import {
		createUniqueString,
		uniqueArr
	} from "@/utils";
	import ElUploadImage from "@/components/el-upload-image.vue";
	import {
		Editor,
		Toolbar
	} from "@wangeditor/editor-for-vue";
	import {
		post,
		get
	} from "@/assets/js/http.js";

	export default {
		name: "view-sku",
		components: {
			SkuSelect,
			SkuTable,
			ElUploadImage,
			Editor,
			Toolbar
		},
		data() {
			return {
				props: {
					label: "name",
					value: "id",
					children: "child",
					checkStrictly: true
				},
				id: '',
				goodsTypeData: [],
				editor: null,
				toolbarConfig: {},
				editorConfig: {
					MENU_CONF: {
						uploadImage: {
							fieldName: "file",
							server: "/admin/ajax/upload",
							headers: {
								batoken: this.$store.state.token
							},
							customInsert(res, insertFn) {
								insertFn("https://zdcloud.zxkjnc.com" + res.data.file.url);
							}
						}
					}
				},
				mode: "default",
				activeTab: "1",
				addValues: [],
				specification: [],
				formData: {
					goods_name: "",
					purchase_num:'',
					goods_no:'',
					categoryIds: [],
					goods_source: '',
					// score_rate:0,
					source_name: '',
					goods_price: "",
					line_price: "",
					imagesIds: [],
					serviceIds: [],
					goods_weight: "",
					spec_type: 10,
					status: 10,
					is_special: 0,
					is_points_gift: 0,
					is_points_discount: 0,
					is_enable_grade: 1,
					is_alone_grade: 0,
					stock_num: "0",
					content: "",
					agent_price: '',
					// block_ids:'',
					is_recommend: 0,
					goods_stuff: 0,
				},
				formRules: {},
				datalist: [],
				sourcelist: [{
					title: '自有商品',
					id: 1
				}, {
					title: '寄卖商品',
					id: 2
				}], //商品属性 1自有商品 2寄卖商品
				userlist: [],
				title: '请上传 336rpx * 336rpx 的图片'
			};
		},
		mounted() {
			this.getGoodsTypeData();
			this.id = this.$route.query.id
			console.log(this.id)
			this.getgoodsinfo(this.id)
			this.getuserlist()
		},
		computed: {
			disabled() {
				return (
					this.specification.length > 3 ||
					this.specification.some(item => !item.value)
				);
			},
			// 过滤掉属性名和属性值为空的数据规格项目map
			specificationFilter() {
				return this.specification.filter(
					item => item.value && item.leaf.length
				);
			}
		},
		methods: {
			async getuserlist() {
				const data = await get({
					url: "/admin/user.RealmeritUser/index",
					loading: true,
					params: {
						page: 1,
						limit: 9999
					}
				});
				this.userlist = data.list;
			},
			async getGoodsTypeData() {
				//this.$store.state.type 1供应商，2 商家
				if (this.$store.state.type == 2) {
					const data = await get({
						url: "/admin/shop.MerchGoodsCategory/index",
						loading: true,
						params: {
							page: 1,
							limit: 999
						}
					});
					this.goodsTypeData = data.list;
				} else {
					const data = await get({
						url: "/admin/shop.GoodsCategory/levelCate",
						loading: true,
						params: {
							page: 1,
							limit: 999
						}
					});
					this.goodsTypeData = data.list;
				}
			},
			changeValuegoods_price(e) {
				this.$forceUpdate()
				this.formData.goods_price = e
				console.log(e, 'e')
			},
			changeValueline_price(e) {
				this.$forceUpdate()
				this.formData.line_price = e
				console.log(e, 'e')
			},
			changeValueagent_price(e) {
				this.$forceUpdate()
				this.formData.line_price = e
				console.log(e, 'e')
			},
			changeValuegoods_weight(e) {
				this.$forceUpdate()
				this.formData.goods_weight = e
				console.log(e, 'e')
			},
			changeValuestock_num(e) {
				this.$forceUpdate()
				this.formData.stock_num = e
				console.log(e, 'e')
			},
			getgoodsinfo(id) {
				get({
					url: '/admin/shop.Goods/detail',
					params: {
						goodsId: id
					}
				}).then(res => {
					this.formData = res.row.goodsInfo
					this.formData.imagesIds = [{
						name: res.row.goodsInfo.goods_images[0].full_url,
						url: res.row.goodsInfo.goods_images[0].full_url
					}]
					console.log(this.formData.imagesIds, 'this.formData.imagesIds')
					this.formData.categoryIds = res.row.goodsInfo.categoryIds[0]
					this.formData.content = res.row.goodsInfo.content
					if (res.row.goodsInfo.spec_type == 20) {
						this.formData.skuList.forEach((item) => {
							if (item.image) {
								item.image = [{
									name: item.image.name,
									id: item.image.id,
									full_url: item.image.full_url,
									url: item.image.url,
								}]
							} else {
								item.image = [{
									name: '',
									id: 0,
									full_url: '',
									url: '',
								}]
							}

						})
						res.row.goodsInfo.specList.forEach((el) => {
							this.specification.push({
								id: el.spec_id,
								value: el.spec_name,
								name: el.spec_name,
								leaf: el.valueList.map(item => {
									return {
										value: item.spec_value,
										id: item.spec_value_id,
									}
								})
							});
						});
					} else {
						this.formData.goods_price = res.row.goodsInfo.skuList[0].goods_price
						// this.formData.line_price = res.row.goodsInfo.skuList[0].line_price
						this.formData.stock_num = res.row.goodsInfo.skuList[0].stock_num
						this.formData.goods_weight = res.row.goodsInfo.skuList[0].goods_weight
						this.formData.line_price = res.row.goodsInfo.skuList[0].line_price
						this.formData.block_ids = res.row.goodsInfo.skuList[0].block_ids
						// this.formData.source_name = res.row.goodsInfo.skuList[0].source_name
					}

					const skuList = res.row.goodsInfo.skuList

					this.datalist = [...skuList]
					// this.specification = res.row.goodsInfo.specList[0].valueList
					console.log(res, this.specificationFilter, res.row.goodsInfo.skuList, skuList)
					this.$nextTick(() => {
						this.specification = [...this.specification]
					})
				})
			},
			// async getGoodsTypeData() {
			// 	const data = await get({
			// 		url: "/admin/shop.GoodsCategory/index",
			// 		loading: true,
			// 		params: {
			// 			page: 1,
			// 			limit: 999
			// 		}
			// 	});
			// 	this.goodsTypeData = data.list;
			// },
			onCreated(editor) {
				this.editor = Object.seal(editor);
			},
			addSpec() {
				this.specification.push({
					id: createUniqueString() + "_id",
					value: "",
					leaf: []
				});
			},
			delSepc(index) {
				this.specification.splice(index, 1);
			},
			addOption(index) {
				let str = this.addValues[index] || "";
				str = str.trim();
				if (!str) return;
				const oldArr = this.specification[index].leaf;
				const arr = str
					.split(/\s+/) // 使用空格分割成数组
					.filter(value => !oldArr.some(option => option.value === value)) // 过滤掉 oldArr 已存在的 value
					.map(value => ({
						id: createUniqueString() + "_id",
						value
					})); // 把 value 转成对象，id 设置为 null 
				this.specification[index].leaf = uniqueArr([...oldArr, ...arr]);
				this.$set(this.addValues, index, "");
			},
			delOption(spec_index, option_index) {
				this.specification[spec_index].leaf.splice(option_index, 1);
			},
			async submit() {
				const formData = JSON.parse(JSON.stringify(this.formData));
				// if(formData.spec_type == 10&&!formData.block_ids&&this.formData.line_price){
				// 	this.$message('请选择要屏蔽的用户')
				// 	return
				// }
				console.log(formData, 'formData')
				if (formData.spec_type == 20) {
					const specList = [];
					this.specificationFilter.forEach(item => {
						const specItem = {};
						specItem.key = item.id;
						specItem.spec_name = item.value;
						specItem.valueList = [];
						item.leaf.forEach(sitem => {
							specItem.valueList.push({
								key: sitem.id,
								groupKey: item.value,
								spec_value: sitem.value
							});
						});
						specList.push(specItem);
					});
					console.log(this.specificationFilter, 'this.specificationFilter')
					const skuData = this.$refs.skuTable.getData();
					const skuList = [];
					console.log(skuData, 'skuData')
					skuData.forEach(item => {
						const skuItem = {
							id: item.id,
							goods_price: item.goods_price,
							goods_sku_no: item.goods_sku_no,
							goods_weight: item.goods_weight,
							image_id: item.image ?
								item.image[0].id : "",
							// line_price: item.line_price,
							stock_num: item.stock_num,
							line_price: item.line_price,
							// ids:item.ids,imagesIds
							skuKeys: []
						};
						item.skus.forEach((sitem, sindex) => {
							const pindex = specList.findIndex(
								ssitem => ssitem.spec_name === sitem.k
							);
							const cindex = specList[pindex].valueList.findIndex(
								ssitem => ssitem.spec_value === sitem.v
							);
							skuItem.skuKeys.push({
								groupKey: pindex,
								valueKey: cindex
							});
							skuItem["spec_value_" + sindex] = sitem.v;
						});
						skuList.push(skuItem);
					});
					formData.specData = {
						skuList: skuList,
						specList: specList
					};
					formData.imagesIds = formData.goods_images.map(item => {
						return item.id;
					});
				} else {
					formData.imagesIds = formData.goods_images.map(item => {
						return item.id;
					});
					formData.skuList[0].goods_price = this.formData.goods_price
					formData.skuList[0].line_price = this.formData.line_price
					// formData.skuList[0].line_price = this.formData.line_price
					formData.skuList[0].goods_weight = this.formData.goods_weight
					formData.skuList[0].stock_num = this.formData.stock_num
					// formData.skuList[0].block_ids = this.formData.block_ids
				}
				console.log(formData.specData, 'formData.specData,data', formData)
				if(Array.isArray(formData.categoryIds)){
					formData.categoryIds = formData.categoryIds
				}else{
					formData.categoryIds = [formData.categoryIds]
				}
				// formData.categoryIds = [formData.categoryIds]
				// console.log(formData.imagesIds, 'formData.imagesIds')groupKey
				await post({
					url: "/admin/shop.goods/edit",
					data: formData,
					loading: true,
					successTip: true
				});
				this.$router.back();
			}
		},
		beforeDestroy() {
			const editor = this.editor;
			if (editor == null) return;
			editor.destroy();
		}
	};
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>

<style scoped>
	.sku {
		margin: 15px;
	}

	.sku_container {
		width: 100%;
		font-size: 12px;
		color: #666;
		padding: 10px;
		border: 1px solid #e5e5e5;
		margin-bottom: 15px;
	}

	.remove {
		display: none;
		position: absolute;
		z-index: 2;
		width: 18px;
		height: 18px;
		font-size: 14px;
		line-height: 16px;
		color: #fff;
		text-align: center;
		cursor: pointer;
		background: rgba(0, 0, 0, 0.3);
		border-radius: 50%;
	}

	.sku_group {
		margin-bottom: 10px;
	}

	.sku_group:hover .spec_title .remove {
		display: block;
	}

	.spec_title {
		position: relative;
		padding: 7px 10px;
		background-color: #f8f8f8;
		line-height: 16px;
		font-weight: 400;
	}

	.spec_title .input {
		width: 200px;
	}

	.spec_title .remove {
		top: 12px;
		right: 10px;
	}

	.group_container {
		padding: 10px 10px 0;
	}

	.group_container .input {
		width: 250px;
	}

	.group_container .sku_item {
		background-color: #f8f8f8;
		padding: 10px;
		display: inline-block;
		margin-right: 10px;
		vertical-align: middle;
		text-align: center;
		position: relative;
		border-radius: 2px;
		cursor: pointer;
	}

	.group_container .sku_item:hover .remove {
		display: block;
	}

	.group_container .sku_item .remove {
		top: -8px;
		right: -8px;
	}

	.group_container .sku_item .text {
		display: block;
		width: 74px;
		margin: 0 auto;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
</style>